const connection = require('../app/database');

class userService {

  // 将user存储到数据库
  async create(user) {
    const {nickname, password} = user;
    try {
      const statement = `insert into user (nickname, password) values (?,?)`;  // 定义sql语句
      const result = await connection.execute(statement, [nickname, password]);  // 执行sql语句
      return result[0];  // 返回结果
    } catch (error) {
      console.log(error);
    }
  }

  // 根据用户名返回用户
  async getUserByNickname(nickname) {

    try {
      const statement = `select * from user where nickname = ?`;
      const result = await connection.execute(statement, [nickname]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 保存用户头像路径
  async updateAvatarByUserId(avatarUrl, userId) {
    try {
      const statement = `UPDATE user SET avatar_url = ? WHERE id = ?`;
      const result = await connection.execute(statement, [avatarUrl, userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 保存用户cover路径
  async updateCoverByUserId(coverUrl, userId) {
    try {
      const statement = `UPDATE user SET cover_url = ? WHERE id = ?`;
      const result = await connection.execute(statement, [coverUrl, userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 注销用户
  async remove(userId) {
    try {
      const statement = `DELETE FROM user WHERE id = ?`;
      const result = await connection.execute(statement, [userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 判断用户是否开放博客
  async isPrivate(userId) {
    try {
      const statement = `SELECT private FROM user WHERE id = ?`;
      const [isPrivate] = await connection.execute(statement, [userId]);
      return isPrivate && ((isPrivate[0]['private'] === 1) ? true : false);
    } catch (error) {
      console.log(error);
    }
  }

  // 更改博客权限
  async update(userId, isPrivate) {
    try {
      const statement = `UPDATE user SET private = ? WHERE id = ?`;
      const result = await connection.execute(statement, [isPrivate, userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 修改用户密码
  async updatePassword(password, userId) {
    try {
      const statement = `UPDATE user SET password = ? WHERE id = ?`;
      const result = await connection.execute(statement, [password, userId]);
      return result[0];
    } catch (error) {
      console.log(error);
    }
  }

  // 修改信条
  async setCreed(userId, creed) {
    try {
      const statement = `UPDATE user SET creed = ? WHERE id = ?`;
      const result = await connection.execute(statement, [creed, userId]);
      return result[0];
    } catch (error) {
      console.log(error)
    }
  }

}

module.exports = new userService();
